<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/default}">
<head>
    <title>销售团队管理</title>
    <style>
        .team-container {
            padding: 20px;
        }
        .team-card {
            margin-bottom: 20px;
            border: 1px solid #eee;
            border-radius: 5px;
            padding: 15px;
        }
        .team-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        .team-members {
            margin-top: 15px;
        }
        .member-item {
            display: flex;
            align-items: center;
            padding: 8px;
            border-bottom: 1px solid #f0f0f0;
        }
        .member-item:last-child {
            border-bottom: none;
        }
        .member-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
            font-weight: bold;
            color: #495057;
        }
        .member-info {
            flex: 1;
        }
        .member-name {
            font-weight: 500;
        }
        .member-role {
            font-size: 12px;
            color: #6c757d;
        }
        .member-actions {
            display: flex;
            gap: 5px;
        }
        .modal-body {
            max-height: 500px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div layout:fragment="content">
        <div class="team-container">
            <div class="card">
                <div class="card-header">
                    <h2 class="card-title">销售团队管理</h2>
                    <button class="btn btn-primary" onclick="showAddTeamModal()">创建团队</button>
                </div>
                <div class="card-body">
                    <!-- 筛选区域 -->
                    <div class="filter-section mb-4">
                        <h4>团队成员筛选</h4>
                        <div class="d-flex mb-3 gap-2">
                            <div class="form-group mr-2">
                                <label for="searchTeam">搜索:</label>
                                <input type="text" class="form-control" id="searchTeam" placeholder="输入成员名称">
                            </div>
                            <div class="form-group mr-2">
                                <label for="filterRole">角色:</label>
                                <select class="form-control" id="filterRole">
                                    <option value="">所有角色</option>
                                    <option value="leader">团队领导</option>
                                    <option value="manager">销售经理</option>
                                    <option value="member">销售代表</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="filterRegion">区域:</label>
                                <select class="form-control" id="filterRegion">
                                    <option value="">所有区域</option>
                                </select>
                            </div>
                            <div class="form-group d-flex align-items-end ml-2">
                                <button class="btn btn-primary" onclick="filterTeamMembers()">筛选</button>
                                <button class="btn btn-secondary ml-2" onclick="resetFilters()">重置</button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 团队成员列表 -->
                    <div id="team-members-list" class="row mb-4">
                        <!-- 团队成员将在这里动态加载 -->
                    </div>

                    <!-- 示例团队列表 -->
                    <div id="team-list">
                        <h4>团队列表</h4>
                        <!-- 示例团队 -->
                        <div class="team-card">
                            <div class="team-header">
                                <h3>核心销售团队</h3>
                                <span class="badge badge-success">活跃</span>
                            </div>
                            <p>负责主要客户和大型企业的销售活动</p>
                            <div class="d-flex justify-content-between">
                                <div>
                                    <strong>团队领导:</strong> 张三
                                </div>
                                <div>
                                    <strong>成员数:</strong> 5
                                </div>
                            </div>
                            <div class="team-members">
                                <h4>团队成员</h4>
                                <div class="member-item">
                                    <div class="member-avatar">张</div>
                                    <div class="member-info">
                                        <div class="member-name">张三</div>
                                        <div class="member-role">团队领导</div>
                                    </div>
                                    <div class="member-actions">
                                        <button class="btn btn-sm btn-outline-danger" onclick="removeMember(1, 101)">移除</button>
                                    </div>
                                </div>
                                <div class="member-item">
                                    <div class="member-avatar">李</div>
                                    <div class="member-info">
                                        <div class="member-name">李四</div>
                                        <div class="member-role">销售经理</div>
                                    </div>
                                    <div class="member-actions">
                                        <button class="btn btn-sm btn-outline-primary" onclick="changeRole(1, 102)">变更角色</button>
                                        <button class="btn btn-sm btn-outline-danger" onclick="removeMember(1, 102)">移除</button>
                                    </div>
                                </div>
                                <div class="member-item">
                                    <div class="member-avatar">王</div>
                                    <div class="member-info">
                                        <div class="member-name">王五</div>
                                        <div class="member-role">销售代表</div>
                                    </div>
                                    <div class="member-actions">
                                        <button class="btn btn-sm btn-outline-primary" onclick="changeRole(1, 103)">变更角色</button>
                                        <button class="btn btn-sm btn-outline-danger" onclick="removeMember(1, 103)">移除</button>
                                    </div>
                                </div>
                            </div>
                            <div class="d-flex justify-content-between mt-3">
                                <button class="btn btn-sm btn-success" onclick="addMembers(1)">添加成员</button>
                                <div>
                                    <button class="btn btn-sm btn-primary mr-2" onclick="editTeam(1)">编辑团队</button>
                                    <button class="btn btn-sm btn-danger" onclick="deleteTeam(1)">删除团队</button>
                                </div>
                            </div>
                        </div>
                        
                        <div class="team-card">
                            <div class="team-header">
                                <h3>新市场拓展团队</h3>
                                <span class="badge badge-primary">新团队</span>
                            </div>
                            <p>负责开拓新行业市场和客户群体</p>
                            <div class="d-flex justify-content-between">
                                <div>
                                    <strong>团队领导:</strong> 赵六
                                </div>
                                <div>
                                    <strong>成员数:</strong> 3
                                </div>
                            </div>
                            <div class="team-members">
                                <h4>团队成员</h4>
                                <div class="member-item">
                                    <div class="member-avatar">赵</div>
                                    <div class="member-info">
                                        <div class="member-name">赵六</div>
                                        <div class="member-role">团队领导</div>
                                    </div>
                                    <div class="member-actions">
                                        <button class="btn btn-sm btn-outline-danger" onclick="removeMember(2, 104)">移除</button>
                                    </div>
                                </div>
                                <div class="member-item">
                                    <div class="member-avatar">钱</div>
                                    <div class="member-info">
                                        <div class="member-name">钱七</div>
                                        <div class="member-role">销售代表</div>
                                    </div>
                                    <div class="member-actions">
                                        <button class="btn btn-sm btn-outline-primary" onclick="changeRole(2, 105)">变更角色</button>
                                        <button class="btn btn-sm btn-outline-danger" onclick="removeMember(2, 105)">移除</button>
                                    </div>
                                </div>
                            </div>
                            <div class="d-flex justify-content-between mt-3">
                                <button class="btn btn-sm btn-success" onclick="addMembers(2)">添加成员</button>
                                <div>
                                    <button class="btn btn-sm btn-primary mr-2" onclick="editTeam(2)">编辑团队</button>
                                    <button class="btn btn-sm btn-danger" onclick="deleteTeam(2)">删除团队</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 添加/编辑团队模态框 -->
        <div id="teamModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 1000;">
            <div style="background-color: white; margin: 5% auto; width: 600px; border-radius: 5px; overflow: hidden;">
                <div style="background-color: var(--primary-color); color: white; padding: 15px 20px;">
                    <h3 id="teamModalTitle">创建销售团队</h3>
                </div>
                <div class="modal-body" style="padding: 20px;">
                    <form id="teamForm">
                        <div class="form-group">
                            <label for="teamName">团队名称</label>
                            <input type="text" class="form-control" id="teamName" required>
                        </div>
                        <div class="form-group">
                            <label for="teamDescription">团队描述</label>
                            <textarea class="form-control" id="teamDescription" rows="3"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="teamLeader">团队领导</label>
                            <select class="form-control" id="teamLeader" required>
                                <option value="">选择团队领导</option>
                                <option value="101">张三</option>
                                <option value="102">李四</option>
                                <option value="103">王五</option>
                                <option value="104">赵六</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div style="padding: 15px 20px; border-top: 1px solid #eee; text-align: right;">
                    <button class="btn btn-secondary mr-2" onclick="closeTeamModal()">取消</button>
                    <button class="btn btn-primary" onclick="saveTeam()">保存</button>
                </div>
            </div>
        </div>
        
        <!-- 添加成员模态框 -->
        <div id="memberModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 1000;">
            <div style="background-color: white; margin: 5% auto; width: 600px; border-radius: 5px; overflow: hidden;">
                <div style="background-color: var(--primary-color); color: white; padding: 15px 20px;">
                    <h3>添加团队成员</h3>
                </div>
                <div class="modal-body" style="padding: 20px;">
                    <form id="memberForm">
                        <div class="form-group">
                            <label>选择要添加的成员</label>
                            <div class="member-selection">
                                <div class="form-check mb-2" th:each="i : ${#numbers.sequence(1, 5)}">
                                    <input class="form-check-input" type="checkbox" name="selectedUsers" th:value="${100 + i}" th:id="'user-' + ${100 + i}">
                                    <label class="form-check-label" th:for="'user-' + ${100 + i}">
                                        用户名称 [[${100 + i}]]
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="memberRole">分配角色</label>
                            <select class="form-control" id="memberRole" required>
                                <option value="销售代表">销售代表</option>
                                <option value="销售经理">销售经理</option>
                                <option value="销售顾问">销售顾问</option>
                                <option value="销售助理">销售助理</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div style="padding: 15px 20px; border-top: 1px solid #eee; text-align: right;">
                    <button class="btn btn-secondary mr-2" onclick="closeMemberModal()">取消</button>
                    <button class="btn btn-primary" onclick="saveMemberAddition()">添加成员</button>
                </div>
            </div>
        </div>
        
        <!-- 更改角色模态框 -->
        <div id="roleModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 1000;">
            <div style="background-color: white; margin: 5% auto; width: 400px; border-radius: 5px; overflow: hidden;">
                <div style="background-color: var(--primary-color); color: white; padding: 15px 20px;">
                    <h3>更改成员角色</h3>
                </div>
                <div class="modal-body" style="padding: 20px;">
                    <form id="roleForm">
                        <input type="hidden" id="changeMemberId">
                        <input type="hidden" id="changeTeamId">
                        <div class="form-group">
                            <label for="newRole">选择新角色</label>
                            <select class="form-control" id="newRole" required>
                                <option value="团队领导">团队领导</option>
                                <option value="销售经理">销售经理</option>
                                <option value="销售代表">销售代表</option>
                                <option value="销售顾问">销售顾问</option>
                                <option value="销售助理">销售助理</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div style="padding: 15px 20px; border-top: 1px solid #eee; text-align: right;">
                    <button class="btn btn-secondary mr-2" onclick="closeRoleModal()">取消</button>
                    <button class="btn btn-primary" onclick="saveRoleChange()">保存</button>
                </div>
            </div>
        </div>

        <!-- 添加团队成员模态框 -->
        <div id="teamMemberModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 1000;">
            <div style="background-color: white; margin: 5% auto; width: 600px; border-radius: 5px; overflow: hidden;">
                <div style="background-color: var(--primary-color); color: white; padding: 15px 20px;">
                    <h3 id="modalTitle">添加团队成员</h3>
                </div>
                <div class="modal-body" style="padding: 20px;">
                    <form id="teamMemberForm">
                        <div class="form-group">
                            <label for="memberName">成员姓名</label>
                            <input type="text" class="form-control" id="memberName" required>
                        </div>
                        <div class="form-group">
                            <label for="memberRole">角色</label>
                            <select class="form-control" id="memberRole" required>
                                <option value="leader">团队领导</option>
                                <option value="manager">销售经理</option>
                                <option value="member">销售代表</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="memberEmail">邮箱</label>
                            <input type="email" class="form-control" id="memberEmail">
                        </div>
                        <div class="form-group">
                            <label for="memberPhone">电话</label>
                            <input type="tel" class="form-control" id="memberPhone">
                        </div>
                        <div class="form-group">
                            <label for="memberRegion">区域</label>
                            <select class="form-control" id="memberRegion">
                                <option value="">选择区域</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="memberTarget">销售目标</label>
                            <input type="number" class="form-control" id="memberTarget" min="0" value="0">
                        </div>
                    </form>
                </div>
                <div style="padding: 15px 20px; border-top: 1px solid #eee; text-align: right;">
                    <button class="btn btn-secondary mr-2" onclick="closeModal()">取消</button>
                    <button class="btn btn-primary" onclick="saveTeamMember()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <th:block layout:fragment="scripts">
        <script>
            let currentTeamId = null;
            let teamMembers = []; // 存储团队成员数据
            
            function showAddTeamModal() {
                document.getElementById('teamModalTitle').textContent = '创建销售团队';
                document.getElementById('teamForm').reset();
                document.getElementById('teamModal').style.display = 'block';
            }
            
            function editTeam(teamId) {
                document.getElementById('teamModalTitle').textContent = '编辑销售团队';
                // 在实际应用中，这里会通过API获取团队详情
                
                // 模拟填充表单数据
                if (teamId === 1) {
                    document.getElementById('teamName').value = '核心销售团队';
                    document.getElementById('teamDescription').value = '负责主要客户和大型企业的销售活动';
                    document.getElementById('teamLeader').value = '101';
                } else if (teamId === 2) {
                    document.getElementById('teamName').value = '新市场拓展团队';
                    document.getElementById('teamDescription').value = '负责开拓新行业市场和客户群体';
                    document.getElementById('teamLeader').value = '104';
                }
                
                document.getElementById('teamModal').style.display = 'block';
            }
            
            function closeTeamModal() {
                document.getElementById('teamModal').style.display = 'none';
            }
            
            function saveTeam() {
                const form = document.getElementById('teamForm');
                if (!form.checkValidity()) {
                    form.reportValidity();
                    return;
                }
                
                const teamName = document.getElementById('teamName').value;
                const teamDescription = document.getElementById('teamDescription').value;
                const teamLeader = document.getElementById('teamLeader').value;
                
                // 在实际应用中，这里会将数据发送到服务器
                console.log({
                    name: teamName,
                    description: teamDescription,
                    leaderId: teamLeader
                });
                
                alert("团队已保存！");
                closeTeamModal();
            }
            
            function deleteTeam(teamId) {
                if (confirm("确定要删除此销售团队吗？")) {
                    // 在实际应用中，这里会调用API删除团队
                    alert("删除团队 ID: " + teamId);
                }
            }
            
            function addMembers(teamId) {
                currentTeamId = teamId;
                document.getElementById('memberForm').reset();
                document.getElementById('memberModal').style.display = 'block';
            }
            
            function closeMemberModal() {
                document.getElementById('memberModal').style.display = 'none';
            }
            
            function saveMemberAddition() {
                const form = document.getElementById('memberForm');
                if (!form.checkValidity()) {
                    form.reportValidity();
                    return;
                }
                
                const selectedUsers = Array.from(document.querySelectorAll('input[name="selectedUsers"]:checked')).map(checkbox => checkbox.value);
                const role = document.getElementById('memberRole').value;
                
                if (selectedUsers.length === 0) {
                    alert("请至少选择一个成员");
                    return;
                }
                
                // 在实际应用中，这里会将数据发送到服务器
                console.log({
                    teamId: currentTeamId,
                    userIds: selectedUsers,
                    role: role
                });
                
                alert("成员已添加！");
                closeMemberModal();
            }
            
            function removeMember(teamId, userId) {
                if (confirm("确定要移除此成员吗？")) {
                    // 在实际应用中，这里会调用API移除成员
                    alert("从团队 " + teamId + " 移除成员 ID: " + userId);
                }
            }
            
            function changeRole(teamId, userId) {
                document.getElementById('changeTeamId').value = teamId;
                document.getElementById('changeMemberId').value = userId;
                document.getElementById('roleForm').reset();
                document.getElementById('roleModal').style.display = 'block';
            }
            
            function closeRoleModal() {
                document.getElementById('roleModal').style.display = 'none';
            }
            
            function saveRoleChange() {
                const form = document.getElementById('roleForm');
                if (!form.checkValidity()) {
                    form.reportValidity();
                    return;
                }
                
                const teamId = document.getElementById('changeTeamId').value;
                const userId = document.getElementById('changeMemberId').value;
                const newRole = document.getElementById('newRole').value;
                
                // 在实际应用中，这里会将数据发送到服务器
                console.log({
                    teamId: teamId,
                    userId: userId,
                    role: newRole
                });
                
                alert("角色已更新！");
                closeRoleModal();
            }

            document.addEventListener('DOMContentLoaded', function() {
                loadTeamMembers();
                loadRegions();
                
                // 设置表单提交事件
                const teamMemberForm = document.getElementById('teamMemberForm');
                if (teamMemberForm) {
                    teamMemberForm.addEventListener('submit', function(e) {
                        e.preventDefault();
                        saveTeamMember();
                    });
                }
            });

            // 从服务器加载团队成员
            function loadTeamMembers() {
                fetch('/crm/api/sales/team/list')
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            teamMembers = result.data;
                            renderTeamMembers();
                        } else {
                            console.error('加载团队成员失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载团队成员失败:', error));
            }
            
            // 渲染团队成员列表
            function renderTeamMembers() {
                const container = document.getElementById('team-members-list');
                if (!container) {
                    console.warn('找不到team-members-list元素，可能在当前页面不需要显示团队成员列表');
                    return; // 如果元素不存在，直接返回
                }
                
                container.innerHTML = '';
                
                teamMembers.forEach(member => {
                    const memberCard = document.createElement('div');
                    memberCard.className = 'team-member-card';
                    
                    // 计算KPI完成率
                    const kpiPercentage = Math.round((member.completedSales / member.targetSales) * 100) || 0;
                    const kpiClass = kpiPercentage >= 100 ? 'success' : 
                                    kpiPercentage >= 70 ? 'warning' : 'danger';
                    
                    memberCard.innerHTML = `
                        <div class="member-header">
                            <img src="${member.avatar || '/assets/img/default-avatar.png'}" alt="${member.name}" class="member-avatar">
                            <h3>${member.name}</h3>
                            <span class="member-role">${member.role}</span>
                        </div>
                        <div class="member-details">
                            <p><strong>电话:</strong> ${member.phone || '未设置'}</p>
                            <p><strong>邮箱:</strong> ${member.email || '未设置'}</p>
                            <p><strong>所属区域:</strong> ${member.region || '全国'}</p>
                            <div class="kpi-container">
                                <p><strong>销售业绩:</strong> ${member.completedSales}/${member.targetSales} (${kpiPercentage}%)</p>
                                <div class="kpi-bar">
                                    <div class="kpi-progress ${kpiClass}" style="width: ${Math.min(kpiPercentage, 100)}%"></div>
                                </div>
                            </div>
                            <div class="member-stats">
                                <div class="stat-item">
                                    <span>${member.activeClients || 0}</span>
                                    <small>活跃客户</small>
                                </div>
                                <div class="stat-item">
                                    <span>${member.pendingDeals || 0}</span>
                                    <small>进行中交易</small>
                                </div>
                                <div class="stat-item">
                                    <span>${member.completedDeals || 0}</span>
                                    <small>完成交易</small>
                                </div>
                            </div>
                            <div class="member-actions">
                                <button onclick="viewTeamMember(${member.id})">查看详情</button>
                                <button onclick="editTeamMember(${member.id})">编辑</button>
                                <button onclick="deleteTeamMember(${member.id})">删除</button>
                            </div>
                        </div>
                    `;
                    
                    container.appendChild(memberCard);
                });
            }

            function showAddMemberModal() {
                document.getElementById('modalTitle').textContent = '添加团队成员';
                document.getElementById('teamMemberForm').reset();
                
                // 移除可能存在的成员ID
                document.getElementById('teamMemberForm').removeAttribute('data-id');
                
                document.getElementById('teamMemberModal').style.display = 'block';
            }

            function closeModal() {
                document.getElementById('teamMemberModal').style.display = 'none';
            }

            function editTeamMember(memberId) {
                document.getElementById('modalTitle').textContent = '编辑团队成员';
                
                // 获取成员详情
                fetch(`/crm/api/sales/team/member/${memberId}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            const member = result.data;
                            
                            // 填充表单
                            document.getElementById('memberName').value = member.name;
                            document.getElementById('memberRole').value = member.role;
                            document.getElementById('memberEmail').value = member.email || '';
                            document.getElementById('memberPhone').value = member.phone || '';
                            document.getElementById('memberRegion').value = member.region || '';
                            document.getElementById('memberTarget').value = member.targetSales || 0;
                            
                            // 设置表单成员ID用于保存
                            document.getElementById('teamMemberForm').setAttribute('data-id', member.id);
                            
                            document.getElementById('teamMemberModal').style.display = 'block';
                        } else {
                            console.error('加载成员详情失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载成员详情失败:', error));
            }
            
            function viewTeamMember(memberId) {
                // 跳转到成员详情页面
                window.location.href = `/crm/sales/team/member/${memberId}`;
            }
            
            function deleteTeamMember(memberId) {
                if (confirm('确定要删除这名团队成员吗？')) {
                    fetch(`/crm/api/sales/team/delete/${memberId}`, {
                        method: 'DELETE'
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            // 刷新团队成员列表
                            loadTeamMembers();
                        } else {
                            alert('删除团队成员失败: ' + result.message);
                        }
                    })
                    .catch(error => {
                        console.error('删除团队成员失败:', error);
                        alert('系统错误，请稍后重试');
                    });
                }
            }
            
            function saveTeamMember() {
                const memberForm = document.getElementById('teamMemberForm');
                const memberId = memberForm.getAttribute('data-id');
                const isEdit = !!memberId;
                
                const memberData = {
                    name: document.getElementById('memberName').value,
                    role: document.getElementById('memberRole').value,
                    email: document.getElementById('memberEmail').value,
                    phone: document.getElementById('memberPhone').value,
                    region: document.getElementById('memberRegion').value,
                    targetSales: parseFloat(document.getElementById('memberTarget').value) || 0
                };
                
                if (isEdit) {
                    memberData.id = parseInt(memberId);
                }
                
                const url = isEdit ? '/crm/api/sales/team/update' : '/crm/api/sales/team/add';
                const method = isEdit ? 'PUT' : 'POST';
                
                fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(memberData)
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        // 关闭模态框，重新加载团队成员列表
                        closeModal();
                        loadTeamMembers();
                    } else {
                        alert('保存团队成员失败: ' + result.message);
                    }
                })
                .catch(error => {
                    console.error('保存团队成员失败:', error);
                    alert('系统错误，请稍后重试');
                });
            }
            
            function filterTeamMembers() {
                const searchTerm = document.getElementById('searchTeam').value.toLowerCase();
                const roleFilter = document.getElementById('filterRole').value;
                const regionFilter = document.getElementById('filterRegion').value;
                
                // 构建过滤条件
                const params = new URLSearchParams();
                if (searchTerm) params.append('search', searchTerm);
                if (roleFilter) params.append('role', roleFilter);
                if (regionFilter) params.append('region', regionFilter);
                
                // 发送带参数的请求
                fetch(`/crm/api/sales/team/list?${params.toString()}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            teamMembers = result.data;
                            renderTeamMembers();
                        } else {
                            console.error('筛选团队成员失败:', result.message);
                        }
                    })
                    .catch(error => console.error('筛选团队成员失败:', error));
            }
            
            function resetFilters() {
                document.getElementById('searchTeam').value = '';
                document.getElementById('filterRole').value = '';
                document.getElementById('filterRegion').value = '';
                loadTeamMembers(); // 重新加载所有成员
            }
            
            // 加载可用区域
            function loadRegions() {
                fetch('/crm/api/common/regions')
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            const regions = result.data;
                            const regionSelect = document.getElementById('memberRegion');
                            const filterRegion = document.getElementById('filterRegion');
                            
                            // 确保元素存在再操作
                            if (regionSelect) {
                                regionSelect.innerHTML = '<option value="">选择区域</option>';
                                
                                regions.forEach(region => {
                                    const option = document.createElement('option');
                                    option.value = region.code;
                                    option.textContent = region.name;
                                    regionSelect.appendChild(option.cloneNode(true));
                                });
                            }
                            
                            if (filterRegion) {
                                filterRegion.innerHTML = '<option value="">所有区域</option>';
                                
                                regions.forEach(region => {
                                    const option = document.createElement('option');
                                    option.value = region.code;
                                    option.textContent = region.name;
                                    filterRegion.appendChild(option);
                                });
                            }
                        }
                    })
                    .catch(error => console.error('加载区域失败:', error));
            }
        </script>
    </th:block>
</body>
</html> 